package com.iotek.bookstore.web.controlle;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件上传
 * apache fileupload
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取FileItemFactory对象
        FileItemFactory factory = new DiskFileItemFactory();

        // 通过工厂类，构造Servlet文件上传类
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        // 从请求中读取数据内容，并封装成FileItem对象
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);

            // 遍历FileItem，获取表单数据
            for (FileItem item : fileItems) {
                // 判断上传的文件内容类型
                if (item.isFormField()) {
                    // 基本的表单字符串数据
                    String value = item.getString();
                    System.out.println("内容描述：" + value);
                } else {
                    // 上传的文件
                    String fileName = item.getName();
                    String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                    String saveFileName = System.currentTimeMillis() + suffix;

                    System.out.println("saveFileName=" + saveFileName);

                    long fileSize = item.getSize();
                    if (fileSize > 0) {
                        // 文件保存
                        String path = getServletContext().getRealPath("/");
                        System.out.println("getServletContext().getRealPath()=" + path);
                        File file = new File(path, saveFileName);
                        System.out.println("file = " + file.getPath());
                        item.write(file);

                        req.getSession().setAttribute("path",saveFileName);
                        // 提示成功，显示图标
                        resp.getWriter().print("1");
                        //resp.getWriter().print("<img src=" + "/" + saveFileName + "></img>");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
